<template>
    <div class="plaid-root" :style="bigBoxInfo.css">
        <div v-for="(item, index) in butInfoArr" :key="index" class="info-tag" :style="item.css" @click="item.action">
            <div v-if="item.component">
                <component :is="componentDict[item.component.key].comp"
                    v-bind="componentDict[item.component.key].props">
                </component>
            </div>
            <div v-else v-html="item.title">
            </div>
        </div>
    </div>
</template>

<script setup>
import { onMounted, ref, shallowRef } from "vue";
import { test_ClickEvent, createConfig_ClickEvent, login_ClickEvent, logOff_ClickEvent, gtoTelegram_ClickEvent, randomOrder_ChangeEvent } from "./event.js"
import { useUserStores } from "../../../../../stores/modules/user.js";
import mySwitch from "@/components/form/switch/index.vue";
import myMessageBoards from './item/messageBoards.vue'



const userStores = useUserStores();

const props = defineProps({
    backPath: String
})
const emits = defineEmits(["updateConfig"]);

//#region
const backImage = ref(props.backPath);
let posiArr = [];
const butInfoArr = ref([]);
const componentDict = ref({});
const cubeInfo = {
    width: 40,
    margin: 7,
}
const bigBoxInfo = {
    width: 0,
    margin: 0,
};
//#endregion


onMounted(() => {
    if (userStores.getConfigAction().randomOrder) {
        into();
        randomOrder();
    } else
        main();
})


const into = () => {
    const config = userStores.getConfigAction();
    const userCode = userStores.userCode;

    //#region 加载config按钮
    butInfoArr.value.push({
        title: 'CreateConfig',
        action: createConfig_ClickEvent,
        width: 3,
        height: 1,
    });
    butInfoArr.value.push({
        title: 'UpdateConfig',
        action: () => { emits('updateConfig', 1) },
        width: 3,
        height: 1,
    });
    butInfoArr.value.push({
        title: 'Test',
        action: test_ClickEvent,
        width: 2,
        height: 1,
    });
    //#endregion

    //#region 加载用户Code
    if (userCode) {
        butInfoArr.value.push({
            title: userCode.toUpperCase(),
            action: () => { },
            css: 'user-select:auto;',
            width: 5,
            height: 1,
        });
        butInfoArr.value.push({
            title: "LogOFF",
            action: () => { logOff_ClickEvent(main); },
            width: 2,
            height: 1,
        });
    } else {
        butInfoArr.value.push({
            title: '<input id="userCodeInput" value="sy_92c7e22e374b53a6" placeholder="userCode" />',
            action: () => { },
            width: 5,
            height: 1,
        })
        butInfoArr.value.push({
            title: 'Login',
            action: () => { login_ClickEvent(main); },
            width: 2,
            height: 1,
        })
    }
    //#endregion

    //#region 第三方讨论组
    butInfoArr.value.push({
        title: '<img id="telegram-cover" src="/src/static/icon/telegram_cover.jpg"/>',
        action: () => { },
        width: 2,
        height: 2,
    });
    butInfoArr.value.push({
        title: '<img id="telegram-icon" src="/src/static/icon/telegram_icon.png"/>Telegram',
        action: gtoTelegram_ClickEvent,
        width: 3,
        height: 1,
    });
    //#endregion

    //#region 设置
    butInfoArr.value.push({
        title: 'Order',
        action: randomOrder,
        width: 2,
        height: 1,
    });
    butInfoArr.value.push({
        component: {
            key: 'mySwitchOfRandomOrder',
            comp: mySwitch,
            props: {
                case: ['Random Order NO', 'Random Order OFF'],
                default: config.randomOrder == 1 ? true : false,
                change: randomOrder_ChangeEvent,
            },
        },
        action: () => { },
        width: 5,
        height: 1,
    });
    butInfoArr.value.push({
        title: 'Notice',
        action: () => { router.push({ path: '/notice', }) },
        width: 2,
        height: 1,
    });
    butInfoArr.value.push({
        component: {
            key: 'messageBoards',
            comp: myMessageBoards,
        },
        action: () => { router.push({ path: '/message', }) },
        width: 4,
        height: 1,
    });
    //#endregion
}

const main = (isInto = true) => {
    if (isInto) {
        butInfoArr.value = [];
        posiArr = [];
        into();
    }

    const { width, margin } = cubeInfo;
    createRow();
    bigBoxInfo.width = posiArr[0].length * (width + margin) - margin;
    bigBoxInfo.margin = (window.innerWidth - bigBoxInfo.width) / 2;
    bigBoxInfo.css += `width:${bigBoxInfo.width}px;margin-left:${bigBoxInfo.margin}px;`;

    // randomTest(10);

    for (let i = 0; i < butInfoArr.value.length; i++) {
        const element = butInfoArr.value[i];
        const [w, h] = [element.width, element.height];
        //开始检索
        const posi = findNullPlaid(w, h, element.title);
        if (posi) {
            setPosi(w, h, posi[0], posi[1])
            const [x, y] = [posi[0] * (margin + width), margin + posi[1] * (margin + width)]
            const [wC, hC] = [(width + margin) * w - margin, (width + margin) * h - margin];
            butInfoArr.value[i].css += `;height:${hC}px;width:${wC}px;top:${y}px;left:${x}px;line-height:${hC}px;`
        }
        //加入组件
        if (element.component) {
            componentDict.value[element.component.key] = {
                comp: shallowRef(element.component.comp),
                props: element.component.props,
            }
        }
    }
    // console.log(posiArr, butInfoArr.value)
    bigBoxInfo.css += `height:${posiArr.length * (width + margin) + margin}px;`;

}

//#region 计算css
const randomOrder = () => {
    const tempButInfoArr = butInfoArr.value;
    const tempButInfoArr1 = [];
    for (let i = 0; i < tempButInfoArr.length; i++) {
        const index = parseInt(Math.random() * tempButInfoArr.length);
        tempButInfoArr1.push(tempButInfoArr[index]);
        tempButInfoArr.splice(index, 1);
        i--;
        if (tempButInfoArr.length == 1) {
            tempButInfoArr1.push(tempButInfoArr[0]);
            break;
        }
    }
    //重定位
    butInfoArr.value = tempButInfoArr1;
    posiArr = [];
    main(false);
}
const randomTest = (count) => {
    for (let i = 0; i < count; i++) {
        const w = parseInt(Math.random() * 2 + 1);
        const h = parseInt(Math.random() * 2 + 1);
        const r = parseInt(Math.random() * 255 + 1);
        const g = parseInt(Math.random() * 255 + 1);
        const b = parseInt(Math.random() * 255 + 1);
        const temp = {
            title: i,
            width: w,
            height: h,
            color: [r, g, b],
        };
        if (butInfoArr.value[count]) {
            butInfoArr.value[count] = temp;
        } else {
            butInfoArr.value.push(temp);
        }
    }
    // console.log(butInfoArr);
}

const findNullPlaid = (w, h, index) => {
    for (let i = 0; i < posiArr.length; i++) {
        // 如果全行为空 加一行
        let count = 0;
        for (let p = 0; p < posiArr[i].length; p++) {
            count += posiArr[i][p];
        }
        if (count == posiArr[i].length) {
            if (i == posiArr.length - 1) {
                createRow();
            }
            continue;
        }

        for (let p = 0; p < posiArr[i].length; p++) {
            const element = posiArr[i][p];
            if (element == 0) {//为空
                //查看下一个(w)
                let wBool = true;
                // console.log(index, p + (w - 1) + 1, posiArr[i].length, i, p)
                if (p + w <= posiArr[i].length) {
                    for (let t = 1; t < w; t++) {
                        const tempW = posiArr[i][p + t];
                        if (tempW == 1) {
                            wBool = false;
                            break;
                        }
                    }
                } else {
                    wBool = false;
                }

                //查看下一个(h)
                let hBool = true;
                if (wBool) {
                    if (h == 1) {

                    } else {
                        for (let t = 1; t < h; t++) {
                            if (i + t >= posiArr.length) {
                                createRow();
                            }
                            if (posiArr[i + t][p] == 1) {
                                hBool = false;
                                break;
                            }
                        }
                    }
                }

                if (wBool && hBool) {
                    return [p, i];
                }
            }
        }
        if (i == posiArr.length - 1) {
            // console.log(index, posiArr)
            createRow();
        }
    }

    // console.log(index, butInfoArr.value)
    return null;
}

const setPosi = (w, h, x, y) => {
    for (let i = 0; i < h; i++) {
        for (let p = 0; p < w; p++) {
            posiArr[i + y][p + x] = 1;
        }
    }
}

const createRow = () => {
    const { width, margin } = cubeInfo;
    if (posiArr.length == 0) {
        const windowWidth = window.innerWidth;
        const count = parseInt((windowWidth - margin) / (width + margin));
        var cur = [];
        for (let i = 0; i < count; i++) {
            cur.push(0);
        }
        posiArr.push(cur);
    } else {
        var cur = [];
        for (let i = 0; i < posiArr[0].length; i++) {
            cur.push(0);
        }
        posiArr.push(cur);
    }
    return posiArr;
}
//#endregion


</script>

<style lang="scss">
.plaid-root {
    position: relative;
    height: 5px;
    // background: red;

    .info-tag {
        position: absolute;
        text-align: center;
        line-height: 30px;
        background-image: v-bind(backImage);
        background-attachment: fixed;
        background-size: cover;
        background-position: center;
        transition-duration: 0.3s;
        user-select: none;
        font-weight: 900;
        border-radius: 7px;

        >div {
            width: 100%;
            height: 100%;
            display: flex;
            justify-content: center;
            align-items: center;
            background: rgba(255, 255, 255, 0.3);
            border-radius: 7px;
        }
    }

    .info-tag:active {
        // border-radius: 30px;
        box-shadow: inset 0 0 10px -5px black, 0 0 10px -3px black;
    }

    #mySwitch {
        width: 90%;
        height: 100%;
    }

    #telegram-cover {
        width: 100%;
        background-position: center;
        background-size: contain;
    }

    #telegram-icon {
        height: 60%;
        margin-right: 5px;
    }

    #userCodeInput {
        background: none;
        border: 0px;
        outline: none;
        border-bottom: 2px solid rgba(128, 128, 128, 1);
        text-align: center;
        font-size: 16px;
        padding: 2px 0;
    }

    #userCodeInput:focus {
        border-bottom: 2px solid rgba(128, 128, 128, 1);
    }
}
</style>